package com.nm.service.impl;

import com.nm.commons.exception.SupperException;
import com.nm.commons.util.StringUtil;
import com.nm.orm.dao.ArticleDao;
import com.nm.orm.dao.pageParam.ArticleBackPageInput;
import com.nm.orm.dao.pageParam.ArticlePageInput;
import com.nm.orm.model.State;
import com.nm.orm.pojo.ArticleEntity;
import com.nm.orm.pojo.out.ArticleBackPageOutput;
import com.nm.orm.pojo.out.ArticleOutput;
import com.nm.service.ArticleService;
import com.nm.service.page.PageEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * Created by hewu on 2017/2/15 0015.
 */
@Transactional
@Service("articlesService")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleDao arDao;

    @Override
    public List<ArticleEntity> findAll() throws SupperException {

        return arDao.findAll();
    }

    public PageEntity<ArticleOutput> pageQuery(ArticlePageInput input) {

        return  null;
    }

    @Override
    public PageEntity<ArticleBackPageOutput> backPageQuery(ArticleBackPageInput input) {
        return arDao.backPage(input);
    }

    @Override
    public String insert(ArticleEntity article) {
        article.setState(State.ABLE.dbValue());
        article.setCreatedAt(new Date());
        return arDao.insert(article);
    }

    @Override
    public void saveOrUpdate(ArticleEntity article) {
        if (StringUtil.isNull(article.getId())) {
            article.setCreatedAt(new Date());
        }

        if (0 == article.getState()) {
            article.setState(State.ABLE.dbValue());
        }

        arDao.saveOrUpdate(article);
    }

    @Override
    public void update(ArticleEntity article) throws SupperException {

        if (State.DISABLE.dbValue() == article.getState()) {
            article.setState(State.ABLE.dbValue());
        }

        arDao.saveOrUpdate(article);
    }

    @Override
    public ArticleEntity getById(String id) throws SupperException {
        return arDao.findById(id);
    }

    @Override
    public void delete(ArticleEntity articleEntity) throws SupperException {
        arDao.delete(articleEntity);
    }

    @Override
    public int deleteById(String id) throws SupperException {
        return arDao.deleteById(id);
    }
}
